import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class UdpClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpClient(String ip, int port) throws SocketException {
        serverIp = ip;
        serverPort = port;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        while(true){
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入-> ");
            String request = sc.next();
            DatagramPacket requestPacket = new DatagramPacket(
                    request.getBytes(),
                    request.getBytes().length,
                    InetAddress.getByName(serverIp),
                    serverPort);

            socket.send(requestPacket);


            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            socket.receive(responsePacket);
            System.out.println(responsePacket.getAddress().toString());

            String response = new String(
                    responsePacket.getData(),
                    0,
                    responsePacket.getData().length);

            //System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient client = new UdpClient("127.0.0.1", 9090);
        client.start();
    }


}
